<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JamAlong</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <!-- Le styles -->
    <link href="../static/css/bootstrap.css" rel="stylesheet">
    <style>
      body {
        padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
      }
    </style>
    <link href="../static/css/bootstrap-responsive.css" rel="stylesheet">

    <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

    <!-- Le fav and touch icons -->
    <link rel="shortcut icon" href="../static/ico/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../static/ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../static/ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="../static/ico/apple-touch-icon-57-precomposed.png">
    <script src="../static/js/jquery-1.7.1.js"></script>
    <script src="../static/js/jquery.form.js"></script>
     <script>
        $(document).ready(function () {

            var bar = $('.bar');
            var percent = $('.percent');
            var status = $('#status');
            var order = '';
            var filter = '';
            function getOrderedSongs(params) {

                if (order === ''){
                    if (filter === ''){
                        getSongs('ordering='+params);
                        order = '-';
                    }else{
                        getSongs(filter+'&ordering='+params);
                        order = '-';
                    }
                }else{
                    if (filter === ''){
                        getSongs('ordering='+order+params);
                        order = '';
                    }else{
                        getSongs(filter+'&ordering='+order+params);
                    }
                }
            }
            function getSongs(params) {
                $.getJSON("/api/song/?"+params,
                {
                    format: "json"
                },
                function(json) {
                    var items = [];
                    var elem = [];

                    items = json.objects;

                    $('.table > tbody').remove();

                    for (var i = 0; i < items.length; i++){
                        console.log(items[i].title);
                        elem.push('<tr><td><a href="#" class="icon-play" id="play"/></td>'+
                                '<td>' + items[i].title + '</td>'+
                                '<td>' + items[i].artist + '</td>'+
                                '<td>' + items[i].album + '</td>'+
                                '<td>' + items[i].genre + '</td>'+
                                '</tr>');
                    }
                    $('<tbody/>', {
                        html: elem.join('')
                        }).appendTo('.table');
                });
            }

            function getChords(title) {
                $.getJSON("/api/gp/songs/" + title,
                {
                    format: "json"
                },
                function(json) {
                    var items = [];
                    var elem = [];

                    items = json.objects;

                    $('#chords-container > div').remove();

                    for (var i = 0; i < items.length; i++){
                        var html = '';
                        html += '<p><strong>' + items[i].title + '</strong></p>';
                        var chords = items[i].chords;
                        for (var j = 0; j < chords.length; j++ ) {
                            html += '<img src="'+ chords[j].image_url + '"></img>';
                        }
                        html += '<p><pre>'+ items[i].body +'</pre></p>';
                        elem.push(html);
                    }
                    $('<div/>', {
                        html: elem.join('')
                        }).appendTo('#chords-container');
                });
            }
            function reset_form(){
                $('#uploadFile_span').html($('#uploadFile_span').html());
            }

            $('#upload_form').ajaxForm({
                beforeSend: function() {
                    status.empty();
                    var percentVal = '0%';
                    bar.width(percentVal);
                    percent.html(percentVal);
                },
                uploadProgress: function(event, position, total, percentComplete) {
                    var percentVal = percentComplete + '%';
                    bar.width(percentVal);
                    percent.html(percentVal);
                    //console.log(percentVal, position, total);
                },
                complete: function(xhr) {
                    if(xhr.responseText === 'ok'){
                        $(status).addClass('alert alert-success');
                    }
                    else if(xhr.responseText !== 'error'){
                        $(status).addClass('alert alert-info');
                    }else{
                        $(status).addClass('alert alert-error');
                    }

                    status.html(xhr.responseText);
                    //Clear the file field, status bar and response text
                    setInterval(function(){
                        status.empty();
                        var percentVal = '0%';
                        bar.width(percentVal);
                        percent.html(percentVal);
                        $(status).removeClass('alert');
                        //This disables the file input field after first time use
//                        reset_form();
                    }, 3000);


                    getSongs('');
                }
            });
            $('#filter_form').submit(function(){
                var field = $("#filter-field").val();
                var type = $("#filter-type").val();
                var value = $("#filter-value").val();
                filter = field+type+value;
                console.log(field+type+value);
                getSongs(field+type+value);
                return false;
            });

            $('#btn-filter-song').click(function(){
               $("#filter-content").toggle();
            });
            $('#btn-upload-song').click(function () {
                $("#upload").toggle();
            });
            $("#btn-hide-upload").click(function () {
                $("#btn-upload-song").button('toggle');
                $("#upload").toggle();
            });

            $("#btn-hide-filter").click(function () {
                $("#btn-filter-song").button('toggle');
                $("#filter-content").toggle();
            });

            $("#btn-reset-filter").click(function () {
                getSongs('');
            });

            $('#tbl-songs').on("click", "tr", function(event) {
                var tdItem =  $(this).find("td:eq(1)");
                var tdItemAudio =  $(this).find("td:eq(0)");
                var re = '\/';
                var songTitle = $("#media-player > div").children().children().attr('id');
                var loadNewSong = true;

                if (songTitle) {
                    if (tdItem.text()) {
                        console.log('songTitle= ' + songTitle);
                        console.log('tdItem= ' + tdItem)
                        if (songTitle == tdItem.text()) {
                            $('#media-player > div').remove();
                            tdItemAudio.html('<a href="#" class="icon-play" id="play"/>');
                            loadNewSong = false;
                        } else {
/*                            $("#tbl-songs tr").each(function() {
                                var titleCol = $(this).find("td:eq(1)");
                                var controlCol = $(this).find("td:eq(0)");
                                if (titleCol.text() == songTitle) {
                                    controlCol.html('<a href="#" class="icon-play" id="play"/>');
                                }
                                console.log(titleCol.text());
                            });*/
                            loadNewSong = false;
                        }
                    }
                } if (loadNewSong) {
                    getChords(tdItem.text());
                    $.getJSON("/api/song/?title=" + tdItem.text(),
                    {
                        format: "json"
                    },
                    function(json) {
                        var items = [];
                        var elem = [];
                        var path;
                        var title;

                        items = json.objects;

                        $('#media-player > div').remove();

                        for (var i = 0; i < items.length; i++) {
                            path = items[i].path;
                            title = items[i].title;
                        }

                        var currPath = path.split(re);

                        elem.push('<audio autoplay="autoplay">'+
                                  '<source id="' + title +'" src="/api/song/uploads/' + currPath[1] + '"' + 'type="audio/mpeg"/>'+
                                  'Your browser does not support the audio element.'+
                                  '</audio>');
                        $('<div/>', {
                            html: elem.join('')
                        }).appendTo('#media-player');

                        tdItemAudio.html('<a href="#" class="icon-stop" id="stop"/>');
                    });
                }
            });

            $('#tbl-songs').on("click", "th", function(event) {
                var thItem = $(this).text();
                if ( thItem.trim() === 'Song name' ){
                    getOrderedSongs('title');
                }
                if( thItem.trim() === 'Artist' ){
                    getOrderedSongs('artist');
                }
                if( thItem.trim() === 'Album' ){
                    getOrderedSongs('album');
                }
                if( thItem.trim() === 'Genre' ){
                    getOrderedSongs('genre');
                }
            });

            getSongs();
        });
     </script>
  </head>

  <body>
  <div id="media-player"></div>

    <div class="navbar navbar-fixed-top">
      <div class="navbar-inner">
        <div class="container">
          <a class="brand" href="#">JamAlong</a>
          <div class="btn-toolbar">
            <div class="btn-group">
                <a class="btn btn-mini" data-toggle="button" id="btn-upload-song" href="#">Upload</a>
                <a class="btn btn-mini" data-toggle="button" id="btn-filter-song" href="#">Filter</a>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="container-fluid">
        <div class="row-fluid">
            <div class="span8">
                <div id="filter-content" hidden="hidden">
                    <div class="page-header">
                        <h1>Filter the song list</h1>
                    </div>
                    <form class="well form-inline" id="filter_form" action="#">
                        <div class="controls">
                            <select class="span2" id="filter-field" >
                                <option value="title">Song name</option>
                                <option value="artist">Artist</option>
                                <option value="album">Album</option>
                                <option value="genre">Genre</option>
                            </select>
                            <select class="span2" id="filter-type" >
                                <option value="=">Equals</option>
                                <option value="__icontains=">Contains</option>
                                <option value="__istartswith=">starts with</option>
                            </select>

                            <input type="text" class="input-medium" id="filter-value" name="filter-value" >
                            <input type="submit" class="btn" value="Apply filter ">
                            <div class="btn" id="btn-reset-filter">Reset filter</div>
                            <div class="btn" id="btn-hide-filter">Done</div>
                        </div>
                    </form>
                </div>
                <div class="page-header">
                    <h1>My song book</h1>
                </div>
                <table class="table" id="tbl-songs">
                  <thead>
                    <tr>
                      <th>#</th>
                      <th>
                          <a href="#">Song name</a>
                      </th>
                      <th>
                          <a href="#">Artist</a>
                      </th>
                      <th>
                          <a href="#">Album</a>
                      </th>
                      <th>
                          <a href="#">Genre</a>
                      </th>
                    </tr>
                  </thead>
                </table>
                <div id="result"></div>

            </div>
            <div class="span4">
                <div id="upload" hidden="hidden">
                    <div class="page-header">
                        <h1>Upload new song</h1>
                    </div>
                    <form class="well form-inline" id="upload_form" action="/api/songs/upload" enctype="multipart/form-data">
                        <span id="uploadFile_span" class="inline">
                            <input type="file" class="btn" name="file" >
                        </span>
                        <input type="submit" class="btn" value="Upload ">
                        <div class="btn" id="btn-hide-upload">Done</div>
                        <p>
                        <div class="progress progress-striped">
                            <div class="bar" tyle="width: 40%;"></div >
                        </div>
                        <div id="status"></div>
                        </p>
                    </form>
                </div>

                <div id="chords">
                    <div class="page-header">
                        <h1>Chords</h1>
                    </div>
                    <div id="chords-container"></div>
                </div>
            </div>
        </div>
    </div> <!-- /container -->

    <!-- Le javascript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="../static/js/bootstrap.js"></script>
  </body>
</html>
